package net.huashitong.ssydt.provider.msg.service;

import net.huashitong.comment.vo.HstComment;
import net.huashitong.ssydt.article.entity.SsArticleArticle;
import net.huashitong.ssydt.article.entity.SsArticleType;
import net.huashitong.ssydt.exam.entity.SsExamPaper;
import net.huashitong.ssydt.msg.constant.MessageConsts;
import net.huashitong.ssydt.msg.entity.SsMsgMessage;
import net.huashitong.ssydt.msg.entity.SsMsgRemindConfig;
import net.huashitong.ssydt.msg.entity.SsMsgUserMessage;
import net.huashitong.ssydt.provider.article.service.SsArticleArticleService;
import net.huashitong.ssydt.provider.article.service.SsArticleTypeService;
import net.huashitong.ssydt.provider.comment.service.SdkCommentService;
import net.huashitong.ssydt.provider.exam.service.SsExamPaperService;
import net.huashitong.ssydt.provider.msg.dto.SsApplicationMessage;
import net.huashitong.ssydt.provider.msg.dto.SsSingleMessage;
import net.huashitong.ssydt.provider.push.PushMessage;
import net.huashitong.ssydt.provider.push.service.PushService;
import net.huashitong.ssydt.provider.utils.StringUtils;
import net.huashitong.user.UserManager;
import net.huashitong.user.http.Result;
import net.huashitong.user.results.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.11.15
 */
@Service
@Transactional
public class MsgPushServiceImpl implements MsgPushService {

    private UserManager userManager;

    private SsArticleArticleService ssArticleArticleService;

    private SsExamPaperService ssExamPaperService;

    private PushService pushService;

    private SsMsgMessageService ssMsgMessageService;

    private SsMsgUserMessageService ssMsgUserMessageService;

    private SsMsgRemindConfigService ssMsgRemindConfigService;

    private SdkCommentService sdkCommentService;

    private SsArticleTypeService ssArticleTypeService;

    @Autowired
    public MsgPushServiceImpl(UserManager userManager,
                              SsArticleArticleService ssArticleArticleService,
                              SsExamPaperService ssExamPaperService,
                              PushService pushService,
                              SsMsgMessageService ssMsgMessageService,
                              SsMsgUserMessageService ssMsgUserMessageService,
                              SsMsgRemindConfigService ssMsgRemindConfigService,
                              SdkCommentService sdkCommentService,
                              SsArticleTypeService ssArticleTypeService) {
        this.userManager = userManager;
        this.ssArticleArticleService = ssArticleArticleService;
        this.ssExamPaperService = ssExamPaperService;
        this.pushService = pushService;
        this.ssMsgMessageService = ssMsgMessageService;
        this.ssMsgUserMessageService = ssMsgUserMessageService;
        this.ssMsgRemindConfigService = ssMsgRemindConfigService;
        this.sdkCommentService = sdkCommentService;
        this.ssArticleTypeService = ssArticleTypeService;
    }

    @Override
    public void pushSingleMessage(SsSingleMessage ssSingleMessage) {
        String title = getSingleTitle(ssSingleMessage);
        String text = getSingleText(ssSingleMessage);

        //保存消息表
        SsMsgMessage ssMsgMessage = new SsMsgMessage();
        ssMsgMessage.setTitle(title);
        ssMsgMessage.setText(text);
        ssMsgMessage.setMsgType(ssSingleMessage.getMsgType());
        ssMsgMessage.setTarget(ssSingleMessage.getTarget());
        ssMsgMessage.setTargetType(ssSingleMessage.getTargetType());
        ssMsgMessage.setAction(ssSingleMessage.getAction());
        ssMsgMessage.setSender(ssSingleMessage.getSender());
        ssMsgMessage.setOfflineExpireTime(System.currentTimeMillis());
        ssMsgMessage.setMsgScope(MessageConsts.MsgScope.SINGLE);
        ssMsgMessage.setIsDelete((byte) 0);
        ssMsgMessageService.insert(ssMsgMessage);
        //保存用户消息表
        SsMsgUserMessage ssMsgUserMessage = new SsMsgUserMessage();
        ssMsgUserMessage.setUserId(ssSingleMessage.getRecipient());
        ssMsgUserMessage.setMessageId(ssMsgMessage.getId());
        ssMsgUserMessage.setIsRead((byte) 0);
        ssMsgUserMessage.setIsDelete((byte) 0);
        ssMsgUserMessageService.insert(ssMsgUserMessage);

        //是否推送开关控制
        SsMsgRemindConfig config = ssMsgRemindConfigService.getByUserId(ssSingleMessage.getRecipient());
        if (config != null) {
            if (config.getTotalSwitch() == 0) {
                return;
            }
            if (MessageConsts.Action.REPLY_COMMENT.equals(ssSingleMessage.getAction())
                    && config.getCommentSwitch() == 0) {
                return;
            }

            if (MessageConsts.Action.COMMENT_PRAISES.equals(ssSingleMessage.getAction())
                    && config.getPraiseSwitch() == 0) {
                return;
            }
        }
        //推送消息
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTitle(title);
        pushMessage.setContext(text);
        pushMessage.setMessageId(ssMsgMessage.getId());
        String taskId = pushService.pushMessageToSingle(ssSingleMessage.getRecipient(), pushMessage);
        //记录任务id
        ssMsgMessage.setTaskId(taskId);
        ssMsgMessageService.updateByPrimaryKey(ssMsgMessage);

    }

    @Override
    public void pushMessageToApplication(SsApplicationMessage message) {
        String title = getApplicationTitle(message);
        String text = getApplicationText(message);
        long offlineExpireTime = getOfflineExpireTime(message.getOfflineTimes());

        //保存消息表
        SsMsgMessage ssMsgMessage = new SsMsgMessage();
        ssMsgMessage.setTitle(title);
        ssMsgMessage.setText(text);
        ssMsgMessage.setMsgType(message.getMsgType());
        ssMsgMessage.setTarget(message.getTarget());
        ssMsgMessage.setTargetType(message.getTargetType());
        ssMsgMessage.setSender(message.getSender());
        ssMsgMessage.setOfflineExpireTime(System.currentTimeMillis() + offlineExpireTime);
        ssMsgMessage.setMsgScope(MessageConsts.MsgScope.APPLICATION);
        ssMsgMessage.setIsDelete((byte) 0);
        ssMsgMessageService.insert(ssMsgMessage);

        PushMessage pushMessage = new PushMessage();
        pushMessage.setTitle(title);
        pushMessage.setContext(text);
        pushMessage.setMessageId(ssMsgMessage.getId());
        String taskId = pushService.pushMessageToApp(pushMessage, offlineExpireTime);
        //记录任务id
        ssMsgMessage.setTaskId(taskId);
        ssMsgMessageService.updateByPrimaryKey(ssMsgMessage);

    }

    /**
     * 设置有效期
     *
     * @param offlineTimes
     * @return
     */
    private long getOfflineExpireTime(int offlineTimes) {
        long offlineExpireTime = 86400000L;
        if (offlineTimes > 0) {
            offlineExpireTime = offlineTimes * 60000L;
        }
        return offlineExpireTime;
    }

    /**
     * @param message
     * @return
     */
    private String getApplicationText(SsApplicationMessage message) {
        String text = message.getText();
        if (StringUtils.isBlank(text)) {
            switch (message.getTargetType()) {
                case MessageConsts.TargetType.ARTICLE:
                    SsArticleArticle ssArticleArticle = ssArticleArticleService
                            .getById(Long.parseLong(message.getTarget()));
                    text = ssArticleArticle.getTitle();
                    if (text.length() > 100) {
                        text = text.substring(0, 100);
                    }
                    break;
                case MessageConsts.TargetType.EXAM_TEST:
                    SsExamPaper ssExamPaper = ssExamPaperService.getById(Long.parseLong(message.getTarget()));
                    text = ssExamPaper.getPaperName();
                    break;
                default:
                    text = "";
            }
        }
        return text;
    }

    private String getApplicationTitle(SsApplicationMessage message) {
        String title = message.getTitle();
        if (StringUtils.isBlank(title)) {
            switch (message.getTargetType()) {
                case MessageConsts.TargetType.ARTICLE:
                    SsArticleArticle ssArticleArticle = ssArticleArticleService
                            .getById(Long.parseLong(message.getTarget()));
                    SsArticleType ssArticleType = ssArticleTypeService.getById(ssArticleArticle.getArticleTypeId());
                    title = ssArticleType.getName();
                    break;
                case MessageConsts.TargetType.EXAM_TEST:
                    SsExamPaper ssExamPaper = ssExamPaperService.getById(Long.parseLong(message.getTarget()));
                    title = ssExamPaper.getPaperName();
                    break;
                default:
                    title = "";
            }
        }
        return title;
    }

    /**
     * 推送内容
     *
     * @param ssSingleMessage
     * @return
     */
    private String getSingleText(SsSingleMessage ssSingleMessage) {
        String text = ssSingleMessage.getText();
        if (StringUtils.isBlank(text)) {
            switch (ssSingleMessage.getTargetType()) {
                case MessageConsts.TargetType.ARTICLE:
                case MessageConsts.TargetType.ARTICLE_TEST:
                    SsArticleArticle ssArticleArticle = ssArticleArticleService
                            .getById(Long.parseLong(ssSingleMessage.getTarget()));
                    text = String.format("[资讯]%s", ssArticleArticle.getTitle());
                    break;
                case MessageConsts.TargetType.EXAM_TEST:
                    SsExamPaper ssExamPaper = ssExamPaperService.getById(Long.parseLong(ssSingleMessage.getTarget()));
                    text = String.format("[题库]%s", ssExamPaper.getPaperName());
                    break;
                case MessageConsts.TargetType.COMMENT:
                    HstComment hstComment = sdkCommentService.getComments(Long.parseLong(ssSingleMessage.getTarget()));
                    String content = "";
                    if (hstComment != null) {
                        if (ssSingleMessage.getAction().equals(MessageConsts.Action.AUTHOR_REPLY)) {
                            content = hstComment.getAuthorReply();
                        } else {
                            if (hstComment.getContent().length() > 100) {
                                content = hstComment.getContent().substring(0, 100);
                            } else {
                                content = hstComment.getContent();
                            }

                        }
                    }
                    text = String.format("[评论]%s", content);
                    break;
                default:
                    text = "";
            }
        }

        return text;
    }


    /**
     * 推送标题
     *
     * @param ssSingleMessage
     * @return
     */
    private String getSingleTitle(SsSingleMessage ssSingleMessage) {
        String title = ssSingleMessage.getTitle();
        if (StringUtils.isBlank(title)) {
            String nickname = "";
            String action;
            //昵称
            Result<User> rs = userManager.get(ssSingleMessage.getSender());
            if (rs.getCode().equals(Result.Status.SUCCESS) && rs.getResults() != null) {
                nickname = rs.getResults().getNickname();
            }
            //动作
            switch (ssSingleMessage.getAction()) {
                case MessageConsts.Action.COMMENT_PRAISES:
                    action = "点赞了你的评论";
                    break;
                case MessageConsts.Action.REPLY_COMMENT:
                    action = "回复了你的评论";
                    break;
                case MessageConsts.Action.AUTHOR_REPLY:
                    nickname = "作者";
                    action = "回复了你的评论";
                    break;
                default:
                    action = "";
            }
            title = nickname + action;
        }
        return title;
    }
}
